<?php

namespace mini;

use Exception;

class Template
{
    static public function get_view_module() {

        // 尝试从URL获取view_module
        $url = str_replace('', '', current_url());
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url_bits = explode('/', $url);

        if (empty($url_bits[3])) {
            $view_module = MODULE_NAME;
        } else {
            $view_module = $url_bits[3];
        }

        return $view_module;
    }

    static public function display($data=null) {

        if (!isset($data['view_module'])) {
            $data['view_module'] = self::get_view_module();
        }

        if (!isset($data['view_file'])) {
            $data['view_file'] = 'home';
        }

        $file_path = APP_PATH . $data['view_module'] . '/views/' . $data['view_file'] . '.php';
        self::attempt_include($file_path, $data);
    }

    static public function partial($file_name, $data=null) {
        $file_path = ROOT_PATH.'templates/'.$file_name.'.php';

        self::attempt_include($file_path, $data);
    }

    static public function load($file_name, $data=null)
    {
        $file_path = ROOT_PATH.'app/views/'.$file_name.'.php';

        self::attempt_include($file_path, $data);
    }

    static private function attempt_include($file_path, $data=null) {

        if (file_exists($file_path)) {

            if (isset($data)) {
                extract($data);
            }

            require_once($file_path);
        } else {
            throw new Exception('模板不存在: '.$file_path);
        }

    }

}